<template>
  <n-card
    :size="'small'"
    style="width: 768px"
    role="dialog"
    title="请输入图片验证码"
    :bordered="false"
    aria-modal="true"
  >
    <template #header-extra v-if="showCloseIcon">
      <SvgIcon
        icon="chacha"
        class="cursor-pointer"
        @click="handleClose"
      ></SvgIcon>
    </template>
    <n-divider class="!my-2" />
    <n-form
      ref="formRef"
      :label-width="isSmall ? 100 : 120"
      label-placement="left"
      :label-align="isSmall ? 'left' : 'right'"
      :model="codeForm"
      size="large"
      require-mark-placement="right"
      :rules="codeFormRules"
    >
      <n-form-item label="验证码：" path="name">
        <n-input
          v-model:value="codeForm.code"
          :allow-input="noSideSpace"
          placeholder="请输入验证码"
          clearable
          :maxlength="25"
        />
        <div
          class="ml-[12px] text-gray-400 text-[12px]"
          @click="handleGetPicCode"
          v-html="validateCodeStr"
        ></div>
      </n-form-item>
      <n-form-item label=" ">
        <n-button
          type="primary"
          class="grent-btn w-[120px]"
          @click="handleValidate"
        >
          确定
        </n-button>
      </n-form-item>
    </n-form>
  </n-card>
</template>

<script setup lang="ts">
import type { FormInst } from 'naive-ui'
import { sendPicValidCode } from '@/api/user'
import type { IndexObj } from '@/types/commom'
import { noSideSpace } from '@/utils'
import { userMenuShow } from '@/hooks/useMenuShow'

const { isSmall } = userMenuShow()

withDefaults(
  defineProps<{
    showCloseIcon?: boolean
  }>(),
  {
    showCloseIcon: true
  }
)

const emits = defineEmits<{
  (e: 'visibleChange', value: boolean): void
  (e: 'onFinish', value: string): void
}>()

const codeForm = reactive({
  code: ''
})

const codeFormRules = reactive({
  code: [
    {
      required: true,
      message: '请输入验证码',
      trigger: ['blur']
    }
  ]
})

// 关闭弹窗
const handleClose = () => {
  emits('visibleChange', false)
}

const formRef = ref<FormInst | null>()
const handleValidate = () => {
  // 进行验证码的校验
  formRef.value?.validate((error: any) => {
    if (error) {
      return
    }
    emits('onFinish', codeForm.code)
  })
}

const validateCodeStr = ref('')
// 去获取图片验证码
const handleGetPicCode = () => {
  sendPicValidCode()
    .then((res) => {
      validateCodeStr.value = res.data.img
    })
    .catch(() => {
      ;(window as IndexObj).$message.error('获取验证码失败')
    })
}

onMounted(() => {
  handleGetPicCode()
})
</script>

<style scoped lang="scss"></style>
